// Random number generator - requires a PRNG backend, e.g. prng4.js

// For best results, put code like
// <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'>
// in your main HTML document.

var SecureRandom = (function () {

    "use strict";
    var rng_state;
    var rng_pool;
    var rng_pptr;
    var rng_psize = 256;

    var SecureRandom = function() {
        if (rng_pool === null || rng_pool === undefined) {
            rng_pool = [];
            rng_pptr = 0;
            var t;
            if (navigator.appName === "Netscape" && navigator.appVersion < "5" && window.crypto) {
                // Extract entropy (256 bits) from NS4 RNG if available
                var z = window.crypto.random(32);
                for (t = 0; t < z.length; ++t) {
                    rng_pool[rng_pptr++] = z.charCodeAt(t) & 255;
                }
            }
            // extract some randomness from Math.random()
            while (rng_pptr < rng_psize) {
                t = Math.floor(65536 * Math.random());
                rng_pool[rng_pptr++] = t >>> 8;
                rng_pool[rng_pptr++] = t & 255;
            }
            rng_pptr = 0;
            seedTime();
        }
    };

    var nextBytes = function(ba) {
        var i;
        for (i = 0; i < ba.length; ++i) {
            ba[i] = getBytes();
        }
    };

    var getBytes = function() {
        if (rng_state === null || rng_state === undefined) {
            seedTime();
            rng_state = new RC4();
            rng_state.init(rng_pool);
            for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) {
                rng_pool[rng_pptr] = 0;
            }
            rng_pptr = 0;
        }
        return rng_state.next();
    };

    var seedTime = function() {
        seedInt(new Date().getTime());
    };

    var seedInt = function(x) {
        rng_pool[rng_pptr++] ^= x & 255;
        rng_pool[rng_pptr++] ^= (x >> 8) & 255;
        rng_pool[rng_pptr++] ^= (x >> 16) & 255;
        rng_pool[rng_pptr++] ^= (x >> 24) & 255;
        if (rng_pptr >= rng_psize) {
            rng_pptr -= rng_psize;
        }
    };

    SecureRandom.prototype.nextBytes = nextBytes;

    return SecureRandom;
}());

